package com.zh.demo01.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * Spring Security 配置类
 * 使用默认的配置: formLogin
 * @author ZH
 * @date 23:41 2021/1/7
 */
@Configuration
@EnableWebSecurity//(debug = true)
public class WebSecurityConfig {

    /**
     * Spring Security核心配置
     * 过滤器链的重要配置
     */
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        //加载不需要权限认证的uri
        String[] permitURIs = new String[]{"/open/**"};

        http    //添加自定义的filter
//                .addFilterBefore(Filter(), UsernamePasswordAuthenticationFilter.class)
                .authorizeHttpRequests( expression -> {
                    // 静态资源和actuator相关的请求都放行
                    expression.requestMatchers("/static/**", "/actuator/**").permitAll();

                    // 放行要公开的接口
                    expression.requestMatchers(permitURIs).permitAll();

                    // 以角色，去放行
                    expression.requestMatchers("/vip/**").hasAnyRole("VIP1","VIP2"); //有VIP角色才能访问

                    // 其他请求都要认证
                    expression.anyRequest().authenticated();
                    // 开发方便：开发环境下不认证
//                    expression.anyRequest().permitAll();
                })
                // 登录方式有：form登录、httpBasic登录、oauth2登录、saml2登录、jwt登录
                .formLogin(Customizer.withDefaults()) //表单登录
                .logout(Customizer.withDefaults());
        return http.build();
    }

    /**
     * 登录账号配置
     */
    @Bean
    public UserDetailsService userDetailsService() {
        UserDetails user = User.withDefaultPasswordEncoder()
                .username("apple")
                .password("123456")
                .roles("USER")
                .build();
        UserDetails admin = User.withDefaultPasswordEncoder()
                .username("banana")
                .password("123456")
                .roles("USER", "VIP1")
                .build();
        return new InMemoryUserDetailsManager(user, admin);
    }

}